package com.hotel.writer.lucene.index;

import com.hotel.comm.bean.EnumConstants.ActionType;
import com.hotel.comm.bean.lucene.IndexableBean;
import com.hotel.comm.service.search.ILuceneSearchService;
import com.hotel.comm.spring.SpringBeanProxy;
import org.apache.lucene.document.Document;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.index.IndexWriterConfig;
import org.apache.lucene.index.IndexWriterConfig.OpenMode;
import org.apache.lucene.store.FSDirectory;
import org.apache.lucene.util.Version;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.wltea.analyzer.lucene.IKAnalyzer;

import java.io.File;
import java.io.IOException;

/**
 * 抽象索引Writer类，每个Writer类必须指明消费的索引仓库
 * 一个Writer只能对应一个索引仓库
 *
 * @author XuSemon
 * @date 2015-3-17
 */
public class EjobIndexWriter implements Runnable {
    private static final Logger logger = LoggerFactory.getLogger(EjobIndexWriter.class);
    private static final Version LUCENE_VERSION = Version.LUCENE_44;
    private ILuceneSearchService luceneSearchService = (ILuceneSearchService) SpringBeanProxy.getBean("luceneSearchService");
    /**
     * 索引仓库
     */
    protected IndexStore store;
    /**
     *
     */
    protected IndexWriter indexWriter;

    /**
     * 默认构造函数
     */
    public EjobIndexWriter() {
    }

    /**
     * 构造函数
     *
     * @param store
     * @param filePath
     * @param indexType
     */
    public EjobIndexWriter(IndexStore store) {
        this.store = store;
        this.indexWriter = this.createIndexWriter();
    }

    /**
     * 生成实际创建索引文件的IndexWriter
     *
     * @return
     */
    private IndexWriter createIndexWriter() {
        try {
            IndexWriterConfig iwc = new IndexWriterConfig(LUCENE_VERSION, new IKAnalyzer(false));
            iwc.setOpenMode(OpenMode.CREATE_OR_APPEND);
            return new IndexWriter(FSDirectory.open(new File(store.getFsPath())), iwc);
        } catch (IOException e) {
            throw new RuntimeException(e.getMessage());
        }
    }

    @Override
    public void run() {
        try {
            while (true) {
                IndexableBean indexBean = store.remove();
                if (indexBean == null) {
                    continue;
                }
                logger.info(indexBean.getActionType() + "|" + indexBean.toString());
                if (logger.isDebugEnabled()) {
                    logger.debug(indexBean.toString());
                }
                Document doc = indexBean.getDoc();
                if (indexBean.getActionType().equals(ActionType.SAVE)) {
                    this.indexWriter.addDocument(doc);
                } else if (indexBean.getActionType().equals(ActionType.UPDATE)) {
                    this.indexWriter.updateDocument(indexBean.getTerm(), doc);
                } else if (indexBean.getActionType().equals(ActionType.DELETE)) {
                    this.indexWriter.deleteDocuments(indexBean.getTerm());
                }
                this.indexWriter.commit();
                this.luceneSearchService.clearPosition();
//				IndexProcessThread thread = new IndexProcessThread(indexBean, indexWriter);
//				this.taskExecutor.execute(thread);
//				Thread.sleep(1);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public IndexStore getStore() {
        return store;
    }

    public void setStore(IndexStore store) {
        this.store = store;
    }

    public IndexWriter getIndexWriter() {
        return indexWriter;
    }

    public void setIndexWriter(IndexWriter indexWriter) {
        this.indexWriter = indexWriter;
    }
//	private class IndexProcessThread implements Runnable{
//		/**
//		 * 索引实体类
//		 */
//		private IndexableBean indexBean;
//		/**
//		 * 索引类
//		 */
//		private IndexWriter indexWriter;
//		public IndexProcessThread(IndexableBean indexBean, IndexWriter indexWriter){
//			this.indexBean = indexBean;
//			this.indexWriter = indexWriter;
//		}
//		@Override
//		public void run() {
//			try {
//				Document doc = indexBean.getDoc();
//				if(indexBean.getActionType().equals(ActionType.SAVE)){
//					this.indexWriter.addDocument(doc);
//				}else if (indexBean.getActionType().equals(ActionType.UPDATE)) {
//					this.indexWriter.updateDocument(indexBean.getTerm(), doc);
//				}else if (indexBean.getActionType().equals(ActionType.DELETE)) {
//					this.indexWriter.deleteDocuments(indexBean.getTerm());
//				}
//				this.indexWriter.commit();
//			} catch (Exception e) {
//				e.printStackTrace();
//			}
//		}
//	}
}
